<template>
	<div class="card">
		<el-card class="box-card" v-for="(item,index) in menuForm">
			<div slot="header" class="clearfix">
				<span class="el-icon-collection-tag" style="font-size: 14px; color: #409eff;"> {{item.name}}</span>
				<el-switch v-model="item.checked" style="float: right; padding: 3px 0" @change="changeChecked(item,item.id)"></el-switch>
			</div>
			<div class="text item" v-for="(child,key) in item.children">
				<div class="clearfix">
					<span style="font-size: 12px; color: #666;"> {{child.name}}</span>
					<el-switch v-model="child.checked" style="float: right; padding: 3px 0" @change="changeChildrenChecked(child,item)"></el-switch>
				</div>
			</div>
		</el-card>
	</div>

</template>

<script>
	
	import {Menu} from '@/api/'
	
	export default {
		props: {
		  menuForm: {
		    type: Array
		  },
		  roleId:{
			type: Number  
		  }
		},
		
		methods:{
			//父级开关全选
			changeChecked(item,id){
				this.uploadMenu(item.checked,item.id);
				if(item.checked){
					this.childrenChecked(item.children,true);
				}else{
					this.childrenChecked(item.children,false);
				}
			},
			//子集开关checked
			childrenChecked(children,bool){
				children.forEach((item,index)=>{
					item.checked = bool;
					this.uploadMenu(item.checked,item.id);
				})
			},
			//子级开关全选
			changeChildrenChecked(child,data){
				console.log(data)
				let checkedLength = 0;
				data.children.forEach((item)=>{
					this.uploadMenu(item.checked,item.id);
					if(item.checked){
						checkedLength = checkedLength+1;
					}
				})
				if(checkedLength > 0 ){
					data.checked = true;
				}else{
					data.checked = false;
				};
				this.uploadMenu(data.checked,data.id);
			},
			
			uploadMenu(checked,id){
				if(checked){
					Menu.addrole({role_id:this.roleId,menu_id:id});
				}else{
				    Menu.removerole({role_id:this.roleId,menu_id:id});
				}
			},
		}
	}
</script>

<style lang="less" scoped>
	.clearfix {
		height: 30px;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.box-card {
		margin-bottom: 10px;
		width: 100%;
	}
</style>
